$(function () {
  let layer = layui.layer;
  let laypage = layui.laypage;
  let form = layui.form;

  var q = {
    pagenum: 1, // 页码值，默认请求第一页的数据
    pagesize: 10, // 每页显示几条数据，默认每页显示2条
    cate_id: '', // 文章分类的 Id
    state: '', // 文章的发布状态
  };

  // 渲染页面数据
  myArticle();
  /* function myArticle() {
    axios({
      method: 'get',
      url: 'http://124.223.14.236:8060/home/user/myArticle',
      headers: {
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MTI2LCJ1c2VybmFtZSI6IuS4gOWJquaihSIsIm1vYmlsZSI6IjE4MjY3NzIzNDY1Iiwic2V4IjowLCJwYXNzd29yZCI6IiIsImljb24iOiIiLCJub3RlcyI6IuinguaNruWHuua7oeinguS4g-WIsOS4juWTjeS4pOi-vuWHhuavj-WImemimOW8gOmDqOacuuacr-eOsOWbvemhu-S4lOa7oeiusOOAgiIsImJpcnRoZGF5IjoiMjAxMS0wOC0wMyIsImFkZHJlc3MiOiLmtZnmsZ_nnIEg5rip5bee5biCIOW5s-mYs-WOvyJ9LCJpYXQiOjE2MzU4NjY1MDZ9.G7k3SuNcfFEZEjQgZB33kKhgJiXCwcOy7ZoD1QJJXoo',
      },
      params: {
        // page: 1,
        page: q.pagenum,
        limit: 10,
        // limit: q.pagesize,
      },
    }).then(function (res) {
      console.log(res);
      if (res.status !== 200) {
        return layer.msg('获取文章失败！');
      }
      let list_html = res.data.data.data.map(item => {
        return `
        <li>
          <a href="javascript:;">
            <span class="thumbnail">
              <img class="thumb" src="http://124.223.14.236:8060/${item.pic}" />
            </span>
            <span class="text">
              ${item.title} 【待发布】
            </span>
            <div class="action-btn">
              <button class="btn btn-primary btn-xs" data-id="${item.id}">
                <i class="fa fa-edit"></i>
                &nbsp;修改
              </button>
              <button class="btn btn-success btn-xs" data-id="${item.id}">
                <i class="fa fa-send"></i>
                &nbsp;发布
              </button>
              <button class="btn btn-danger btn-xs" data-id="${item.id}">
                <i class="fa fa-trash"></i>
                &nbsp;删除
              </button>
            </div>
          </a>
        </li>
      `;
      });
      $('.items-01').append(list_html.join(''));
      renderPage(res.data.data.count);
    });
  } */

  function myArticle() {
    axios({
      method: 'get',
      url: 'http://124.223.14.236:8060/home/user/myArticle',
      headers: {
        token: localStorage.getItem('token'),
      },
      params: {
        // page: 1,
        page: q.pagenum,
        limit: 10,
        // limit: q.pagesize,
      },
    }).then(function (res) {
      if (res.status !== 200) {
        return layer.msg('获取文章失败！');
      }
      let list_html;
      if (res.data.data.data.length <= 0) {
        list_html = `<p style="font-size='20px'">您还没有发布文章哦</p>`;
        $('#pageBox').hide();
        $('#find').hide();
        $('.items-01').html(list_html);
      } else {
        $('#pageBox').show();
        $('#find').show();
        list_html = res.data.data.data.map(item => {
          if (item.status === 2) {
            return `
            <li>
              <a href="javascript:;">
                <span class="thumbnail">
                  <img class="thumb" src="http://124.223.14.236:8060/${item.pic}" />
                </span>
                <span class="text">
                  ${item.title} 【已发布】
                </span>
                <span class="text-muted post-views">
                  <i class="fa fa-eye"></i>
                  已阅读(${item.lovenum})
                </span>
                <span class="text-muted post-views">
                  <i class="fa fa-heart"></i>
                  被点赞(${item.click})次
                </span>
                <button class="btn btn-danger btn-xs" data-id="${item.id}">
                    <i class="fa fa-trash"></i>
                    &nbsp;删除
                </button>
              </a>
            </li>
          `;
          } else if (item.status === 1) {
            return `
               <li>
                 <a href="javascript:;">
                   <span class="thumbnail">
                     <img class="thumb" src="http://124.223.14.236:8060/${item.pic}" />
                   </span>
                   <span class="text">
                     ${item.title} 【待发布】
                   </span>
                   <div class="action-btn">
                     <button class="btn btn-primary btn-xs" data-id="${item.id}">
                       <i class="fa fa-edit"></i>
                       &nbsp;修改
                     </button>
                     <button class="btn btn-success btn-xs" data-id="${item.id}">
                       <i class="fa fa-send"></i>
                       &nbsp;发布
                     </button>
                     <button class="btn btn-danger btn-xs" data-id="${item.id}">
                       <i class="fa fa-trash"></i>
                       &nbsp;删除
                     </button>
                   </div>
                 </a>
               </li>
            `;
          }
        });
        $('.items-01').html(list_html.join(''));
      }
      renderPage(res.data.data.count);
    });
  }

  // 定义渲染分页的方法
  function renderPage(count) {
    // 调用 laypage.render() 方法来渲染分页的结构
    laypage.render({
      elem: 'pageBox', // 分页容器的 Id
      count: count, // 总数据条数
      limit: q.pagesize, // 每页显示几条数据
      curr: q.pagenum, // 设置默认被选中的分页
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      limits: [10, 15, 20],
      jump: function (obj, first) {
        /* console.log(first)
        console.log(obj.curr)
        console.log(obj.limit); */
        // 把最新的页码值，赋值到 q 这个查询参数对象中
        q.pagenum = obj.curr;
        // 把最新的条目数，赋值到 q 这个查询参数对象的 pagesize 属性中
        q.pagesize = obj.limit;
        // 根据最新的 q 获取对应的数据列表，并渲染表格
        // initTable()
        if (!first) {
          myArticle();
        }
      },
    });
  }

  // 通过代理的形式，为 btn-primary 按钮绑定点击事件
  $('.items-01').on('click', '.btn-primary', function () {
    location.href = './user-add.html';
    let id = $(this).attr('data-id');
    let title = $(this).parent().siblings('.text').val();
    let img = $(this).parent().siblings('.thumbnail').children().prop('src');
    console.log(title);
    console.log(id);
    console.log(localStorage.getItem('fenlei_id'));

    // Edit(id)
  });

  // 修改的方法
  function Edit(id) {
    axios({
      method: 'post',
      url: 'http://124.223.14.236:8060/home/user/editArticle',
      headers: {
        token: localStorage.getItem(token),
      },
      data: {
        title: title,
        author: 'string',
        cateid: 0,
        tags: localStorage.getItem('fenlei_id'),
        pic: localStorage.getItem('img'),
        content: 'string',
        status: 1,
        id: id,
      },
    }).then(function (res) {
      console.log(res);
      if (res.status !== 200) {
        return layer.msg('修改失败！');
      }
      layer.msg('修改成功');
      myArticle();
    });
  }

  // 为发布文章按钮，绑定点击事件处理函数
  let tags = localStorage.getItem('fenlei_id');
  $('.items-01').on('click', '.btn-success', function () {
    // console.log(localStorage.getItem('fenlei_id'));
    axios({
      method: 'post',
      url: 'http://124.223.14.236:8060/home/user/addArticle',
      headers: {
        token: localStorage.getItem('token'),
      },
      data: {
        title: $('.text').val(),
        author: 'string',
        cateid: 0,
        tags: localStorage.getItem('fenlei_id'),
        pic: localStorage.getItem('img'),
        content: 'string',
        status: 2,
      },
    }).then(function (res) {
      console.log(res);
      if (res.data.errno !== 0) {
        return layer.msg('发布文章失败！');
      }
      layer.msg('发布文章成功！');
      myArticle();
      // location.href = './user-list.html';
      // window.myArticle();
    });
  });

  // 通过代理的形式，为删除按钮绑定点击事件
  $('.items-01').on('click', '.btn-danger', function () {
    let id = $(this).attr('data-id');
    console.log(id);
    // 提示用户是否要删除
    layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
      axios({
        method: 'get',
        url: 'http://124.223.14.236:8060/home/user/delArticle',
        headers: {
          token: localStorage.getItem('token'),
        },
        params: {
          id: id,
        },
      }).then(function (res) {
        console.log(res);
        if (res.status !== 200) {
          return layer.msg('删除失败！');
        }
        layer.msg('删除成功！');
        layer.close(index);
        myArticle();
      });
    });
  });
  /* $('.items-01').on('click', '.btn-danger', function () {
    let index = $(this).attr('data-id');
    // console.log(index);
    Delete(index);
  }); */
  // 删除的方法
  /* function Delete(id) {
    axios({
      method: 'get',
      url: 'http://124.223.14.236:
      8060/home/user/delArticle',
      headers: {
        token:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MTI2LCJ1c2VybmFtZSI6IuS4gOWJquaihSIsIm1vYmlsZSI6IjE4MjY3NzIzNDY1Iiwic2V4IjowLCJwYXNzd29yZCI6IiIsImljb24iOiIiLCJub3RlcyI6IuinguaNruWHuua7oeinguS4g-WIsOS4juWTjeS4pOi-vuWHhuavj-WImemimOW8gOmDqOacuuacr-eOsOWbvemhu-S4lOa7oeiusOOAgiIsImJpcnRoZGF5IjoiMjAxMS0wOC0wMyIsImFkZHJlc3MiOiLmtZnmsZ_nnIEg5rip5bee5biCIOW5s-mYs-WOvyJ9LCJpYXQiOjE2MzU4NjY1MDZ9.G7k3SuNcfFEZEjQgZB33kKhgJiXCwcOy7ZoD1QJJXoo',
      },
      params: {
        id: id,
      },
    }).then(function (res) {
      console.log(res);
      if (res.status !== 200) {
        return layer.msg('删除失败！');
      }
      layer.msg('删除成功');
      myArticle();
    });
  }  */

  // 首页和全局数据
  homePage();
  function homePage() {
    axios({
      method: 'GET',
      url: 'http://124.223.14.236:8060/home/index/index',
    }).then(function (res) {
      // console.log(res);
      // 导航栏
      let strNav = res.data.data.allCate
        .map(item => {
          return `
          <li class="menu-item menu-item-type-taxonomy menu-item-object-category">
              <a href="list.html" id=${item.id}><span class="fa fa-bullhorn iconfont ${item.icon}"></span>${item.catename}</a>
          </li>
          `;
        })
        .join('');
      $('#nav').append(strNav);
    });
  }
  userCenter();
  // 用户中心和退出
  function userCenter() {
    // 没有token的时候隐藏用户中心和退出
    if (localStorage.getItem('token')) {
      let str = `
         <a href="user.html" id="user"><i class="fa fa-user"></i>&nbsp;用户中心</a>
         <a href="javascript:;" class="quit"><i></i>&nbsp;退出</a>`;
      $('.slinks').html(str);
    } else {
      let str = `
          <a href="login.html"><i class="fa fa-hand-o-right"></i>&nbsp;登录</a> |
          <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</a>`;
      $('.slinks').html(str);
    }
    $('#user').on('click', function (e) {
      e.preventDefault();
      if (localStorage.getItem('token')) {
        location.href = 'user.html';
      } else {
        location.href = 'login.html';
      }
    });
    $('.quit').on('click', function (e) {
      layer.confirm('你确定要退出吗?', { icon: 3, title: '退出提示' }, function (index) {
        localStorage.removeItem('token');
        location.reload();

        layer.close(index);
      });
    });
  }
  // 导航栏跳转
  function getNavSkip() {
    $('#nav').on('click', 'a', function (e) {
      e.preventDefault();
      window.open('../list.html?id=' + $(this).attr('id'));
    });
  }
  getNavSkip();
});
